package com.gitee.ixtf.vertx.guice

import com.gitee.ixtf.vertx.classInfoList
import com.gitee.ixtf.vertx.internal.*
import com.google.inject.AbstractModule
import com.google.inject.Provides
import com.google.inject.Singleton
import jakarta.ws.rs.Path

class RestfulGuice(vararg packages: Class<*>) : AbstractModule() {
  private val classList by lazy {
    classInfoList(*packages) { buildList { add(getClassesWithAnnotation(Path::class.java)) } }
  }

  @Singleton
  @Provides
  private fun methodList(): Collection<RestfulMethod> =
      classList
          .flatMap { it.declaredMethods.asIterable() }
          .mapNotNull { if (it.isAnnotationPresent(Path::class.java)) RestfulMethod(it) else null }
          .groupBy { it.route }
          .map { (route, methods) ->
            if (methods.size > 1) throw RuntimeException("Restful 地址重复 [$route]")
            methods.first()
          }
}
